import java.util.Arrays;

public class Solution {
    public static int maxSubarraySumCircular(int[] nums) {
        //拆分为最大子数组和、最小子数组和

        int len = nums.length;
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        int[] f = new int[len];//找最大的
        int[] g = new int[len];//找最小的，再用sum减掉，得到最大的子数组和，再和f的最大值比较

        f[0] = nums[0];
        g[0] = nums[0];

        for (int i = 1; i < len; i++) {
            f[i] = Math.max(f[i - 1] + nums[i], nums[i]);
            g[i] = Math.min(g[i - 1] + nums[i], nums[i]);
        }

        System.out.println(Arrays.toString(f));
        System.out.println(Arrays.toString(g));

        int ret1 = Integer.MAX_VALUE * (-1);
        int ret2 = Integer.MAX_VALUE;

        for (int num : f) {
            ret1 = Math.max(ret1, num);
        }

        for (int num : g) {
            ret2 = Math.min(ret2, num);
        }

        //防止nums里的值全为负数
        return sum == ret2 ? ret1 : Math.max(ret1, sum - ret2);
    }

    public static void main(String[] args) {
        System.out.println(maxSubarraySumCircular(new int[]{-3, -2, -3}));
    }
}
